﻿using Core.Shop.Tool;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Core.Shop.Filter
{
    /// <summary>
    /// 带有检测是否登录的过滤器
    /// </summary>
    public class AuthAttribute : ActionFilterAttribute, IActionFilter
    {
        /// <summary>
        /// 方法触发
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var isDefined = false;
            var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
            if (controllerActionDescriptor != null)
            {
                isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                  .Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)));
            }
            if (isDefined) return;
            var token = filterContext.HttpContext.Request.Headers["Ike-Token"];
            if (string.IsNullOrEmpty(token))
            {
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                filterContext.Result = new JsonResult(new { isSuccess = false, message = "请登录", url = "login" });
            }
            base.OnActionExecuting(filterContext);
        }
        /// <summary>
        /// 不带有登陆验证的过滤器
        /// </summary>
        public class NoPermissionRequiredAttribute : ActionFilterAttribute
        {
            /// <summary>
            /// 方法触发
            /// </summary>
            /// <param name="filterContext"></param>
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                base.OnActionExecuting(filterContext);
            }

        }
    }
}
